package com.analytical.www.base

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.analytical.www.vm.VMData

/**
 *@Auther Shawn
 *创建时间：2023/12/24 12:24
 */
abstract class FragmentBase :Fragment(){
    protected lateinit var contentView:View
    private var isLazyLoaded = false
    protected val mHandler = Handler(Looper.getMainLooper())

    protected val vmData by lazy {
        var vm:VMData? = null
        activity?.let {
            vm = ViewModelProvider(it)[VMData::class.java]
        }
        vm
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppBase.instance.addFrag(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        AppBase.instance.removeFrag(this)
        mHandler.removeCallbacksAndMessages(null)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(getLayoutId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        contentView = view
        if (!isLazyLoad()) {
            lazyInLoad()
        }
    }

    override fun onResume() {
        super.onResume()
        if (isLazyLoad()) {
            lazyInLoad()
        }
    }

    open fun isLazyLoad() = false

    private fun lazyInLoad() {
        if (!isLazyLoaded) {
            isLazyLoaded = true
            lazyLoad()
            initClick()
            getData()
        }
    }

    abstract fun getLayoutId():Int

    abstract fun lazyLoad()
    abstract fun getData()
    abstract fun initClick()
    abstract fun onKeyCodeBack():Boolean
}